package org.example.weblog.controller;

import org.example.weblog.entity.LoginResponse;
import org.example.weblog.entity.User;
import org.example.weblog.jwt.JwtTokenUtil;
import org.example.weblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 用户登录
     *
     * @param user 用户对象
     * @return 登录结果和 token
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        User user1 = userService.getByNameAndPassword(user.getUsername(), user.getPassword());
        if (user1 != null) {
            String token = jwtTokenUtil.generateToken(user.getUsername());
            return ResponseEntity.ok().body(new LoginResponse("登录成功", token));
        } else {
            return ResponseEntity.badRequest().body("登录失败");
        }
    }


}
